<template>
  <el-dialog
    :title="!dataForm.goodsTypeId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="商品分类名" prop="goodsTypeName" label-width="150px">
        <el-input v-model="dataForm.goodsTypeName" placeholder="商品分类名"></el-input>
      </el-form-item>

      <el-form-item label="一级商品分类" prop="parentGoodsTypeId" label-width="150px">
      <template>
        <el-select v-model="dataForm.parentGoodsTypeId" placeholder="新建一级商品分类">
          <el-option
            v-for="item in goodsTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </template>
      </el-form-item>

      <el-form-item label="WAP分类图片" prop="wapDescImg" label-width="150px">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleWapImgSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="wapImgUrl" :src="wapImgUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="PC分类图片" prop="pcDescImg" label-width="150px">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handlePcImgSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="pcImgUrl" :src="pcImgUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="分类广告图片" prop="bannerDescImg" label-width="150px">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleBannerImgSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="bannerImgUrl" :src="bannerImgUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

    <el-form-item label="分类广告URL" prop="bannerUrl" label-width="150px">
      <el-input v-model="dataForm.bannerUrl" placeholder="分类广告URL"></el-input>
    </el-form-item>

    <el-form-item label="分类排序" prop="orderNum" label-width="150px">
      <el-input-number v-model="dataForm.orderNum" controls-position="right" :min="0" label="排序号"></el-input-number>
    </el-form-item>
    <el-form-item label="商品筛选属性标签" prop="choosePropertyId" label-width="150px">
      <template>
        <el-select v-model="dataForm.chooseTypeId1" placeholder="请选择商品筛选类别"
        @change="handelSelectTypeShowProperty">
          <el-option
            v-for="item in chooseTypeOptions1"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-select v-model="dataForm.choosePropertyId"  placeholder="请选择商品筛选属性"
        @change="handelConfirmChooseProperty">
          <el-option
            v-for="item in choosePropertyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </template>
      <div>
      <el-tag
        v-for="tag in propertyTags"
        :key="tag.name"
        :type="tag.type"
        closable
        @close="handleChoosePropertyClose(tag)">
        {{tag.name}}
      </el-tag>
      </div>
    </el-form-item>

    <el-form-item label="评论标签" prop="commentTargetId" label-width="150px">
      <template>
        <el-select v-model="dataForm.chooseTypeId2" placeholder="不选择商品筛选类别"
        @change="handelSelectTypeShowTarget">
          <el-option
            v-for="item in chooseTypeOptions2"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-select v-model="dataForm.commentTargetId"  placeholder="请选择评论标签"
        @change="handelConfirmCommentTarget">
          <el-option
            v-for="item in commentTargetOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </template>
      <div>
      <el-tag
        v-for="tag in commentTags"
        :key="tag.name"
        :type="tag.type"
        closable
        @close="handleCommentTargetClose(tag)">
        {{tag.name}}
      </el-tag>
      </div>
     </el-form-item>

    <el-form-item label="分类描述" prop="goodsTypeDesc" label-width="150px">
      <el-input type="textarea" v-model="dataForm.goodsTypeDesc"></el-input>
    </el-form-item>
     <el-form-item label="状态" size="mini" prop="goodsTypeState" label-width="150px">
        <el-radio-group v-model="dataForm.goodsTypeState">
          <el-radio :label="0">启用</el-radio>
          <el-radio :label="1">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :disabled="submitVisible" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        wapImgUrl: '',
        pcImgUrl: '',
        bannerImgUrl: '',
        uploadUrl: '',
        visible: false,
        submitVisible: false,
        dataForm: {
          goodsTypeId: '',
          goodsTypeName: '',
          parentGoodsTypeId: '',
          wapDescImg: '',
          pcDescImg: '',
          bannerDescImg: '',
          bannerUrl: '',
          orderNum: '',
          goodsTypeState: '',
          goodsTypeLevel: '',
          selectChoosePropertyOptions: [],
          chooseTypeId1: '',
          chooseTypeId2: '',
          selectCommentTargetOptions: [],
          goodsTypeDesc: '',
          choosePropertyId: '',
          commentTargetId: ''
        },
        dataRule: {
          goodsTypeName: [
            { required: true, message: '商品分类名', trigger: 'blur' }
          ],
          wapDescImg: [
            { required: true, message: '请设置wap分类图片', trigger: 'blur' }
          ],
          pcDescImg: [
            { required: true, message: '请设置pc分类图片', trigger: 'blur' }
          ],
          goodsTypeState: [
            { required: true, message: '请设置商品分类状态', trigger: 'blur' }
          ]
        },
        goodsTypeOptions: [],
        chooseTypeOptions1: [],
        chooseTypeOptions2: [],
        choosePropertyOptions: [],
        commentTargetOptions: [],
        propertyTags: [],
        commentTags: []
      }
    },
    methods: {
      init (id) {
        // 初始化上传图片路径
        this.uploadUrl = this.$http.adornUrl(`/pig-file/center/file/upload`)
        // 初始化 商品分类顶级下拉框数据,
        this.$http({
          url: this.$http.adornUrl('/pig-center-biz/shopgoods/shopGoodsType/goodsTypeParentItemList'),
          method: 'get'
        }).then(({data}) => {
          this.goodsTypeOptions = data.items
        }).then(() => {
          // 初始化 加载商品筛选类型列表
          this.$http({
            url: this.$http.adornUrl('/pig-center-biz/shopset/goodsChooseType/chooseTypeItemList1'),
            method: 'get'
          }).then(({data}) => {
            this.chooseTypeOptions1 = data.items
            this.handelSelectTypeShowProperty()
          })
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/pig-center-biz/shopset/goodsChooseType/chooseTypeItemList2'),
            method: 'get'
          }).then(({data}) => {
            this.chooseTypeOptions2 = data.items
            this.handelSelectTypeShowTarget()
          })
        }).then(() => {
          // 初始化页面表单数据
          this.dataForm.goodsTypeState = 0
          this.dataForm.orderNum = 0
          this.dataForm.goodsTypeId = id || ''
          this.dataForm.parentGoodsTypeId = ''
          this.dataForm.wapDescImg = ''
          this.dataForm.pcDescImg = ''
          this.dataForm.bannerDescImg = ''
          this.dataForm.bannerUrl = ''
          this.dataForm.selectChoosePropertyOptions = []
          this.dataForm.selectCommentTargetOptions = []
          this.dataForm.chooseTypeId1 = ''
          this.dataForm.chooseTypeId2 = ''
          this.dataForm.choosePropertyId = ''
          this.dataForm.commentTargetId = ''
          this.wapImgUrl = ''
          this.pcImgUrl = ''
          this.bannerImgUrl = ''
          this.propertyTags = []
          this.commentTags = []
          this.visible = true
          this.submitVisible = false
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          // 获取当前修改数据
          if (this.dataForm.goodsTypeId) {
            this.$http({
              url: this.$http.adornUrl(`/pig-center-biz/shopgoods/shopGoodsType/info`),
              method: 'post',
              params: this.$http.adornParams({
                'id': this.dataForm.goodsTypeId
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                // console.log(data.shopGoodsType)
                // 设置表单中普通数据类型属性
                this.dataForm.goodsTypeName = data.shopGoodsType.goodsTypeName
                this.dataForm.goodsTypeState = data.shopGoodsType.goodsTypeState
                this.dataForm.parentGoodsTypeId = data.shopGoodsType.parentGoodsTypeId
                this.dataForm.orderNum = data.shopGoodsType.orderNum
                this.dataForm.goodsTypeLevel = data.shopGoodsType.goodsTypeLevel
                this.dataForm.wapDescImg = data.shopGoodsType.wapDescImg
                this.dataForm.pcDescImg = data.shopGoodsType.pcDescImg
                this.dataForm.bannerDescImg = data.shopGoodsType.bannerDescImg
                this.dataForm.bannerUrl = data.shopGoodsType.bannerUrl
                this.dataForm.goodsTypeDesc = data.shopGoodsType.goodsTypeDesc
                // 设置wap和pc分类图片
                this.wapImgUrl = data.shopGoodsType.wapDescImg
                this.pcImgUrl = data.shopGoodsType.pcDescImg
                // 如果广告图片不为空才设置图片
                if (data.shopGoodsType.bannerDescImg !== '') {
                  this.bannerImgUrl = data.shopGoodsType.bannerDescImg
                }
                // 设置商品筛选类别和筛选属性为下面标签关联的下拉选项
                this.dataForm.chooseTypeId1 = data.shopGoodsType.goodsChooseTypeId
                this.handelInitChoosePropertyItemList()
                // 初始化已选择的商品筛选属性标签
                let arr1 = data.shopGoodsType.shopGoodsTypeRealChooseList
                if (arr1 !== undefined && arr1.length > 0) {
                  for (let item of arr1) {
                    this.dataForm.selectChoosePropertyOptions.push(item.choosePropertyId)
                    this.propertyTags.push({ name: item.choosePropertyName, type: '' })
                  }
                  console.log(this.dataForm.selectChoosePropertyOptions)
                  console.log(this.propertyTags)
                }
                // 初始化已选择的评论标签
                let arr2 = data.shopGoodsType.shopGoodsTypeRealTargetList
                if (arr2 !== undefined && arr2.length > 0) {
                  for (let item of arr2) {
                    this.dataForm.selectCommentTargetOptions.push(item.commentTargetId)
                    this.commentTags.push({ name: item.commentTargetName, type: '' })
                  }
                }
                this.$forceUpdate()
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.submitVisible = true
            this.$http({
              url: this.$http.adornUrl(`/pig-center-biz/shopgoods/shopGoodsType/${!this.dataForm.goodsTypeId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'goodsTypeId': this.dataForm.goodsTypeId || undefined,
                'goodsTypeName': this.dataForm.goodsTypeName,
                'goodsTypeState': this.dataForm.goodsTypeState,
                'goodsTypeLevel': this.dataForm.goodsTypeLevel,
                'parentGoodsTypeId': this.dataForm.parentGoodsTypeId,
                'wapDescImg': this.dataForm.wapDescImg,
                'pcDescImg': this.dataForm.pcDescImg,
                'bannerDescImg': this.dataForm.bannerDescImg,
                'bannerUrl': this.dataForm.bannerUrl,
                'orderNum': this.dataForm.orderNum,
                'selectChoosePropertyOptions': this.dataForm.selectChoosePropertyOptions,
                'selectCommentTargetOptions': this.dataForm.selectCommentTargetOptions,
                'goodsTypeDesc': this.dataForm.goodsTypeDesc
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },

      // 上传wap分类的图片
      handleWapImgSuccess (res, file) {
        this.wapImgUrl = URL.createObjectURL(file.raw)
        if (res && res.code === 0) {
          // console.log(res.url)
          // 从服务器回应对象中获取图片地址，赋值到wapDescImg
          this.dataForm.wapDescImg = this.loadImage(res.url)
        }
      },

      // 上传pc分类的图片
      handlePcImgSuccess (res, file) {
        this.pcImgUrl = URL.createObjectURL(file.raw)
        if (res && res.code === 0) {
          this.dataForm.pcDescImg = this.loadImage(res.url)
        }
      },

      // 上传广告分类的图片
      handleBannerImgSuccess (res, file) {
        this.bannerImgUrl = URL.createObjectURL(file.raw)
        if (res && res.code === 0) {
          this.dataForm.bannerDescImg = this.loadImage(res.url)
        }
      },

      // 上传图片检查，必须是 jpg格式 大小不能超过2M
      beforeAvatarUpload (file) {
        let temp = ['image/jpeg', 'image/jpg', 'mage/jpeg', 'image/png', 'image/pjpeg', 'image/gif', 'image/bmp', 'image/x-png']
        const isJPG = temp.indexOf(file.type) > -1
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
      // 设置商品分类，关闭和删除界面上商品筛选属性标签
      handleChoosePropertyClose (tag) {
        this.propertyTags.splice(this.propertyTags.indexOf(tag), 1)
        this.dataForm.selectChoosePropertyOptions.splice(this.propertyTags.indexOf(tag), 1)
        console.log(this.dataForm.selectChoosePropertyOptions)
      },
      // 设置商品分类，关闭和删除界面上商品评论标签
      handleCommentTargetClose (tag) {
        this.commentTags.splice(this.commentTags.indexOf(tag), 1)
        this.dataForm.selectCommentTargetOptions.splice(this.commentTags.indexOf(tag), 1)
      },
      // 设置商品分类，选择商品筛选类别，加载商品筛选属性
      handelSelectTypeShowProperty () {
        // 如果选择不同的商品筛选类别，那么前面选择的商品筛选属性取消
        this.dataForm.selectChoosePropertyOptions = []
        this.propertyTags = []
        this.dataForm.choosePropertyId = ''
        this.handelInitChoosePropertyItemList()
      },
      handelInitChoosePropertyItemList () {
        this.$http({
          url: this.$http.adornUrl('/pig-center-biz/shopset/goodsChooseProperty/choosePropertyItemList'),
          method: 'get',
          params: this.$http.adornParams({
            'chooseTypeId': this.dataForm.chooseTypeId1
          })
        }).then(({data}) => {
          this.choosePropertyOptions = data.items
        })
      },
      // 设置商品分类，选择商品筛选类别，加载商品评论标签
      handelSelectTypeShowTarget () {
        this.dataForm.commentTargetId = ''
        this.$http({
          url: this.$http.adornUrl('/pig-center-biz/shopset/goodsCommentTarget/commentTargetItemList'),
          method: 'get',
          params: this.$http.adornParams({
            'chooseTypeId': this.dataForm.chooseTypeId2
          })
        }).then(({data}) => {
          this.commentTargetOptions = data.items
        })
      },

      // 确认选择的商品筛选属性，渲染界面标签
      handelConfirmChooseProperty (value) {
        let obj = {}
        obj = this.choosePropertyOptions.find((item) => {
          return item.value === value
        })
        // 添加前检查是否有重复，否则不添加
        if (this.dataForm.selectChoosePropertyOptions.indexOf(obj.value) === -1) {
          this.propertyTags.push({ name: obj.label, type: '' })
          this.dataForm.selectChoosePropertyOptions.push(obj.value)
          // console.log(this.dataForm.selectChoosePropertyOptions)
        }
      },
      // 确认选择的商品评论标签，渲染界面标签
      handelConfirmCommentTarget (value) {
        let obj = {}
        obj = this.commentTargetOptions.find((item) => {
          return item.value === value
        })
        if (this.dataForm.selectCommentTargetOptions.indexOf(obj.value) === -1) {
          this.commentTags.push({ name: obj.label, type: '' })
          this.dataForm.selectCommentTargetOptions.push(obj.value)
        }
      },
      loadImage (path) {
        return this.$http.adornUrl(`/pig-file/center/file/openImg?url=` + path)
      }
    }
  }
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }
  .avatar {
    width: 78px;
    height: 78px;
    display: block;
  }
  .el-tag + .el-tag {
      margin-left: 10px;
  }
  .el-cascader-menu {
      min-width: 180px;
      box-sizing: border-box;
      color: #606266;
      border: 1px solid #e4e7ed;
  }
  .el-cascader-menu ul {
    display: block;
    list-style: none;
    line-height:30px;
    height:30px;
    padding-left:8px;
    flex-wrap:raw;
  }
  .el-cascader__tags {
      position: absolute;
      left: 0;
      right: 30px;
      top: 50%;
      transform: translateY(-50%);
      display: flex;
      flex-wrap: wrap;
      line-height: normal;
      text-align: left;
      box-sizing: border-box;
  }
</style>
